package sort;

import java.util.Arrays;

public class HeapSort {
    public static void main(String[] args) {
        int[] a = {3, 1, 4, 2, 8, 6, 7, 5};
        heapSort(a);
        System.out.println(Arrays.toString(a));
    }

    public static void buildMaxHeap(int[] a, int i, int len) {
        int temp = a[i];
        for (int j = i * 2; j < len; j *= 2) {
            if (j < len && a[j] < a[j + 1]) {
                ++j;
            }
            if (temp >= a[j]) {
                break;
            }
            a[i] = a[j];
            i = j;
        }
        a[i] = temp;
    }

    public static void heapSort(int[] a) {
        int i;
        for (i = a.length / 2 - 1; i >= 0; i--) {
            buildMaxHeap(a, i, a.length - 1);
        }
        for (i = a.length - 1; i >= 0; i--) {
            int temp = a[0];
            a[0] = a[i];
            a[i] = temp;
            buildMaxHeap(a, 0, i - 1);
        }
    }
}
